
#include "p_comp.h"
#include "data_src.h"

#pragma pack(1)
typedef struct  //频率分析结果
{
	int peak_pos; //主峰位置
	float ratio_peak; //主峰功率比例（主峰左右共10点）
	float ratio_low; //低频功率比例（低频20点）
} S_FRE_ANALYSIS; 
#pragma pack()

extern s16 s_in[S_N]; //信号
extern s16 s_out[S_N]; //信号

//分别存一个通道的电压和电流
s16 s_in1[S_N]; //信号
s16 s_in2[S_N]; //信号

S_FRE_ANALYSIS fre_feature(s16 *in);

void analysis_from_csv(const char *filename) //输入csv文件测试
{
	int i;
	read_pdata_from_csv(filename); //csv数据
	//只看通道1的，电压和电流
	int offset = 0;
	while(1) //电压、电流都是相同的结构
	{
		for(i=0;i<S_N;i++)
		{
			if(offset>=datain.size()) //若输入没有那么多
			{
				return ;
			}
			s_in1[i] = datain[offset].u[0];
			s_in2[i] = datain[offset].u[0+4];
			offset++;
		}
		S_FRE_ANALYSIS r1=fre_feature(s_in1);
		S_FRE_ANALYSIS r2=fre_feature(s_in2);
		printf("%d	%d	%.4f	%.5f	%d	%.4f	%.5f\n",offset,
			r1.peak_pos, r1.ratio_peak, r1.ratio_low,
			r2.peak_pos, r2.ratio_peak, r2.ratio_low);
	}

}
S_FRE_ANALYSIS fre_feature(s16 *in)
{
	S_FRE_ANALYSIS r;
	int i=0;
//1、做实数fft
	for(i=0;i<S_N;i++) { f_s_in[i]=in[i]; }
	fft_ip[0]=0; //每次都重新算
	rdft(S_N, 1, f_s_in, fft_ip, fft_w); //正变换
//2、取主峰
	r.peak_pos=0;
	float total_amp=0; //总功率
	float max_val=0;
	for(i=0;i<S_N/2;i++) //复数个数
	{
		int ind=i*2;
		float amp=sqrt(f_s_in[ind]*f_s_in[ind] + f_s_in[ind+1]*f_s_in[ind+1]);
		total_amp+=amp; //累加总功率
		f_s_in[i] = amp; //改为存储功率谱
		tmp_fre_buf[i]=amp;
		if(amp>max_val)
		{
			r.peak_pos=i;
			max_val=amp;
		}
	}
	int st = r.peak_pos-P_W2;
	int end = r.peak_pos+P_W2; //取主峰前后P_W2个
	if(st<1) st=1;
	if(end>=S_N/2) end=S_N/2-1;
	
	r.ratio_peak = 0;
	for(i=st; i<end; i++) //求主峰的比例
	{
		r.ratio_peak += f_s_in[i];
	}
	r.ratio_peak /= total_amp;

	r.ratio_low = 0;
	for(i=0; i<10; i++) //求低频的比例
	{
		r.ratio_low += f_s_in[i];
	}
	r.ratio_low /= total_amp;

	return r;
}

